package com.brownmunoz.companyjcr;

import java.net.MalformedURLException;
import java.util.Iterator;

import javax.jcr.Credentials;
import javax.jcr.Node;
import javax.jcr.PropertyType;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.nodetype.InvalidNodeTypeDefinitionException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeExistsException;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.NodeTypeTemplate;
import javax.jcr.nodetype.PropertyDefinitionTemplate;

import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CompanyMain {

	/**
	 * @param args
	 * @throws RepositoryException 
	 * @throws MalformedURLException 
	 */
	public static void main(String[] args) throws RepositoryException, MalformedURLException {
		BasicConfigurator.configure();
		Logger logger = LoggerFactory.getLogger(CompanyMain.class);
		
		logger.debug("Foobie");
		
		String xml = "/home/eric/Work/JCR/configuration.xml";
		String dir = "/home/eric/Work/JCR/companies";
		RepositoryConfig config = RepositoryConfig.create(xml, dir);
		Repository repository = RepositoryImpl.create(config);

		//Repository repository = new URLRemoteRepository("http://localhost:8080/rmi");
		Credentials creds = new SimpleCredentials("anonymous", "".toCharArray());
		Session session = repository.login(creds, "default");
		
		
		// addTestNodeType(session);
		
		Node root = session.getRootNode();

		NodeTypeManager manager =  session.getWorkspace().getNodeTypeManager();
		
		NodeType baseType = manager.getNodeType("nt:base");

		System.out.println("foo:" + baseType.getName());
		System.out.println(getNodeTypes(manager));
		
		System.out.println(recurseNodes("", root));
		
		session.logout();
		

	}
	
	@SuppressWarnings("unused")
	public static void setupTree(Session session) throws RepositoryException {
		Node root = session.getRootNode();
		
		Node a = root.addNode("A");
		Node b = root.addNode("B");
		Node c = root.addNode("C");
		
		Node d = c.addNode("D");
		Node e = c.addNode("E");
		
		
	}
	
	@SuppressWarnings("unchecked")
	public static void addTestNodeType(Session session) throws InvalidNodeTypeDefinitionException, NodeTypeExistsException, UnsupportedRepositoryOperationException, RepositoryException {
		/* Retrieve node type manager from the session */
		NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager();

		/* Create node type */
		NodeTypeTemplate nodeType = nodeTypeManager.createNodeTypeTemplate();
		nodeType.setName("ERKFOO");

		/* Create a new property */
		PropertyDefinitionTemplate customProperty = nodeTypeManager.createPropertyDefinitionTemplate();
		customProperty.setName("my_custom_property");
		customProperty.setRequiredType(PropertyType.STRING);
		/* Add property to node type */
		nodeType.getPropertyDefinitionTemplates().add(customProperty);

		/* Register node type */
		nodeTypeManager.registerNodeType(nodeType, false);
	}
	
	public static String recurseNodes (String prefix, Node parent) throws RepositoryException {
		if (! parent.hasNodes()) {
			return prefix + ":" + parent.getName() + "\n";
		} else {
			StringBuilder output = new StringBuilder();
			@SuppressWarnings("unchecked")
			Iterator<Node> iterator = parent.getNodes();
			while (iterator.hasNext()) {
				output.append(recurseNodes(prefix + "/" + parent.getName(), iterator.next()));
			}
			return output.toString();
		}
	}
	
	public static  String getNodeTypes(NodeTypeManager manager) throws RepositoryException {
		StringBuilder retval = new StringBuilder();
		@SuppressWarnings("unchecked")
		Iterator<NodeType> ntIterator = manager.getAllNodeTypes();
		while(ntIterator.hasNext()) {
			retval.append("TYPE: " + ntIterator.next().getName() + "\n");
		}
		
		return retval.toString();
	}

}
